package ge.telasi.tasks.ui.user;

import ge.telasi.tasks.ui.Platform;
import ge.telasi.tasks.ui.PrefUtils;
import ge.telasi.tasks.ui.UIUtils;
import ge.telasi.tasks.ui.comp.CommonDialog;
import ge.telasi.tasks.ui.comp.SimpleTable;
import ge.telasi.tasks.ui.comp.TableModel;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * @author dimitri
 */
public class ServerItemSelectorDialog extends CommonDialog {
    private static final long serialVersionUID = -1506962865674626383L;
    
    static private final String SERVER_ITEMS = "server_items455226a52332";
    private ServerItemTable table;
    private JButton btnSelect;
    private JButton btnCancel;
    private ServerItem serverItem;
    private JButton btnAdd;
    private JButton btnRemove;
    private JButton btnEdit;
    private JButton btnUp;
    private JButton btnDown;

    public ServerItemSelectorDialog(Component comp) {
        super(comp, true);
        initComponents();
        getRootPane().setDefaultButton(btnSelect);
        enableComponents();
    }

    private void initComponents() {
        setSize(420, 300);
        setTitle("აარჩიეთ სერვერი რომელზეც იმუშავებთ");
        setLayout(new BorderLayout());
        add(createCenterComponent(), BorderLayout.CENTER);
        add(createBottomComponent(), BorderLayout.SOUTH);
        add(createTopComponent(), BorderLayout.NORTH);
    }

    private Component createCenterComponent() {
        table = new ServerItemTable();
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                enableComponents();
            }
        });
        return new JScrollPane(table);
    }

    private Component createBottomComponent() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        btnSelect = new JButton("არჩევა");
        btnCancel = new JButton("გაუქმება");
        panel.add(btnSelect, BorderLayout.EAST);
        panel.add(btnCancel, BorderLayout.WEST);
        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                serverItem = null;
                dispose();
            }
        });
        btnSelect.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                serverItem = table.getSelection();
                if (serverItem != null) {
                    dispose();
                }
            }
        });
        return panel;
    }

    private Component createTopComponent() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        btnAdd = new JButton(UIUtils.getIcon16x16("add.png"));
        btnRemove = new JButton(UIUtils.getIcon16x16("delete.png"));
        btnEdit = new JButton(UIUtils.getIcon16x16("pencil.png"));
        btnUp = new JButton(UIUtils.getIcon16x16("arrow_up.png"));
        btnDown = new JButton(UIUtils.getIcon16x16("arrow_down.png"));
        btnAdd.setToolTipText("სერვერის დამატება");
        btnRemove.setToolTipText("სერვერის წაშლა");
        btnEdit.setToolTipText("სერვერის რედაქტირება");
        btnUp.setToolTipText("ზევით");
        btnDown.setToolTipText("ქვევით");
        toolBar.add(btnAdd);
        toolBar.add(btnEdit);
        toolBar.add(btnRemove);
        toolBar.addSeparator();
        toolBar.add(btnUp);
        toolBar.add(btnDown);
        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ServerItemDialog dialog = new ServerItemDialog(ServerItemSelectorDialog.this);
                dialog.setServerItem(null);
                UIUtils.openDialog(dialog);
                if (dialog.isApproved()) {
                    ServerItem item = dialog.getServerItem();
                    table.add(item);
                    resetPreferences();
                }
            }
        });
        btnRemove.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                List<ServerItem> items = table.getSelections();
                if (items != null && !items.isEmpty()) {
                    String msg = Platform.getDefault().getLocaleManager().getMessage("General.deleteByCountMsg", items.size());
                    if (UIUtils.askConfirmation(ServerItemSelectorDialog.this, msg)) {
                        for (ServerItem serverItem : items) {
                            table.remove(serverItem);
                        }
                        resetPreferences();
                    }
                }
            }
        });
        btnEdit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ServerItem item = table.getSelection();
                if (item != null) {
                    ServerItemDialog dialog = new ServerItemDialog(ServerItemSelectorDialog.this);
                    dialog.setServerItem(item);
                    UIUtils.openDialog(dialog);
                    if (dialog.isApproved()) {
                        ServerItemTableModel model = (ServerItemTableModel) table.getModel();
                        int index = model.indexOf(item);
                        ServerItem newItem = dialog.getServerItem();
                        model.setItemAt(index, newItem);
                        table.setSelection(newItem);
                        resetPreferences();
                    }
                }
            }
        });
        btnUp.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ServerItem item = table.getSelection();
                if (item != null) {
                    ServerItemTableModel model = (ServerItemTableModel) table.getModel();
                    int index = model.indexOf(item);
                    boolean first = index == 0;
                    if (!first) {
                        model.removeItem(item);
                        model.addItemAt(index - 1, item);
                        table.setSelection(item);
                        resetPreferences();
                    }
                }
            }
        });
        btnDown.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ServerItem item = table.getSelection();
                if (item != null) {
                    ServerItemTableModel model = (ServerItemTableModel) table.getModel();
                    int index = model.indexOf(item);
                    int total = model.getRowCount();
                    boolean last = index == total - 1;
                    if (!last) {
                        model.removeItem(item);
                        model.addItemAt(index + 1, item);
                        table.setSelection(item);
                        resetPreferences();
                    }
                }
            }
        });
        return toolBar;
    }

    private void resetPreferences() {
        List<ServerItem> items = table.getFullData();
        PrefUtils.putObject(SERVER_ITEMS, items);
    }

    public void refresh() {
        table.refresh();
    }

    public ServerItem getServerItem() {
        return serverItem;
    }

    private void enableComponents() {
        int index = table.getSelectedRow();
        int total = table.getRowCount();
        boolean selected = table.getSelection() != null;
        boolean first = index == 0;
        boolean last = index == total - 1;
        btnAdd.setEnabled(true);
        btnRemove.setEnabled(selected);
        btnEdit.setEnabled(selected);
        btnUp.setEnabled(selected && !first);
        btnDown.setEnabled(selected && !last);
    }

    private class ServerItemTable extends SimpleTable<ServerItem> {
        private static final long serialVersionUID = -128574080325865935L;

        @Override
        public boolean shouldBeConnected() {
            return false;
        }

        @Override
        protected TableModel<ServerItem> createEmptyModel() {
            return new ServerItemTableModel();
        }

        @Override
        protected List<ServerItem> getDataFromServer(Platform pl) throws Exception {
            List<ServerItem> items = (List<ServerItem>) PrefUtils.getObject(SERVER_ITEMS);
            if (items == null || items.isEmpty()) {
                items = new ArrayList<ServerItem>();
                items.add(ServerItem.getDefaultServerItem());
            }
            return items;
        }

        @Override
        protected String getPreferenceName() {
            return "SimpleTable.ServerItemTable";
        }

        @Override
        protected int[] getDefaultColumnWidthes() {
            return new int[] { 100, 100, 50 };
        }
        
    }

    private class ServerItemTableModel extends TableModel<ServerItem> {
        private static final long serialVersionUID = 321059998873942573L;
        static private final int NAME = 0;
        static private final int SERVER = 1;
        static private final int PORT = 2;

        @Override
        public int getColumnCount() {
            return 3;
        }

        @Override
        public Class getColumnClass(int columnIndex) {
            switch(columnIndex) {
                case SERVER:
                case NAME:
                    return String.class;
                case PORT:
                    return Integer.class;
                default:
                    return Object.class;
            }
        }

        @Override
        public String getColumnName(int column) {
            switch(column) {
                case SERVER:
                    return "სერვერი";
                case NAME:
                    return "სახელი";
                case PORT:
                    return "პორტი";
                default:
                    return "?";
            }
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }

        @Override
        public Object getValueAt(int row, int column) {
            ServerItem item = getObjectAt(row);
            switch (column) {
                case NAME:
                    return item.getName();
                case SERVER:
                    return item.getHost();
                case PORT:
                    return item.getPort();
                default:
                    return null;
            }
        }

    }

}
